package server;

import server.Exceptions.AuthenticationConflictException;

import java.util.*;
import java.util.concurrent.ConcurrentHashMap;

public class ClientsProcessor {
    private Map<String, Client> clientsMap;
    private Map<String, String> registeredClients;

    public ClientsProcessor() {
        clientsMap = new ConcurrentHashMap<String, Client>();
        registeredClients = DataBase.getUsers();
    }

    boolean addClientToChat(String name, String password, Client client) throws AuthenticationConflictException {
        if (clientsMap.containsKey(name))
            throw new AuthenticationConflictException();
        if (!registeredClients.containsKey(name))
            return false;
        if (!registeredClients.get(name).equals(password))
            return false;
        clientsMap.put(name, client);
        client.setName(name);
        client.setNewClient(false);
        client.setRoom("GuestRoom");
        return true;
    }

    boolean ifNameRegistered(String name) {
        return registeredClients.containsKey(name);
    }

boolean ifCorrectPassword(String password){
    return registeredClients.containsKey(password);
}
    void removeClientFromChat(String name) {
        clientsMap.remove(name);
    }


    boolean addNewClientToSystem(String name, String password) {
        if (registeredClients.containsKey(name))
            return false;
        registeredClients.put(name, password);
        DataBase.addUser(name, password);
        return true;
    }

    public void sendToAllClients(Message message) {
        Client fromClient = message.getClientFrom();
        String room = message.getRoom();
        String nameTo = message.getNameTo();
        boolean personalSended = false;

        String text = message.getDateTime() + " " + fromClient.getName() + ": " + message.getText();

        for (Client client : clientsMap.values()) {
            if (client.getRoom() == null)
                continue;

            if (room == null) {
                client.sendMessage(text);
                continue;
            }

            if (client.getRoom().equals(room) && (nameTo == null))
                client.sendMessage(text);

            if (nameTo != null && client.getName().equals(nameTo)) {
                text += " (personal)";
                client.sendMessage(text);
                personalSended = true;
                break;
            }
        }
        if (nameTo != null && personalSended == false)
            fromClient.sendMessage("There is no user: " + nameTo);
    }
}
